<template>
    <div class="wrapper">
        <el-form :model="caseinfo" label-width="auto" style="width: 600px">
            <div class="applied-wrapper">
                <div class="applied-content applied-content-up">
                    <span>被申请人信息</span>
                </div>

                <div class="applied-content applied-content-down">
                    <el-form-item label="姓名" class="applied-content-down-item-first">
                        <el-input v-model="caseinfo.respondent.name" />
                    </el-form-item>
                    <el-form-item label="身份证号">
                        <el-input v-model="caseinfo.respondent.idNum" />
                    </el-form-item>
                    <el-form-item label="手机号">
                        <el-input v-model="caseinfo.respondent.phoneNum" />
                    </el-form-item>
                </div>
            </div>
            <!--  <el-form-item label="Activity zone">
                <el-select v-model="form.region" placeholder="please select your zone">
                    <el-option label="Zone one" value="shanghai" />
                    <el-option label="Zone two" value="beijing" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="本金">
                <el-input-number v-model="caseinfo.debt.principal" :min="0" controls-position="right"
                    @change="calculateTotalAmount">
                    <template #suffix>
                        <span>RMB</span>
                    </template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="年利率">
                <el-input-number v-model="caseinfo.debt.annualRate" :min="0" :precision="2" controls-position="right"
                    @change="calculateTotalAmount">
                    <template #suffix>
                        <span>%</span>
                    </template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="借款时间">
                <el-col :span="11">
                    <el-date-picker v-model="caseinfo.debt.loanDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" style="width: 100%" @change="calculateTotalAmount" />
                </el-col>
            </el-form-item>
            <el-form-item label="还款期限">
                <el-col :span="11">
                    <el-date-picker v-model="caseinfo.debt.repayDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" style="width: 100%" @change="calculateTotalAmount" />
                </el-col>
            </el-form-item>

            <div>
                <template v-if="showAdvancedFields">
                    <el-form-item label="逾期利率">
                        <el-input-number v-model="caseinfo.debt.overdueRate" :min="0" :precision="2"
                            controls-position="right" @change="calculateTotalAmount">
                            <template #suffix>
                                <span>%</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="滞纳金">
                        <el-input-number v-model="caseinfo.debt.lateFee" :min="0" controls-position="right"
                            @change="calculateTotalAmount">
                            <template #suffix>
                                <span>RMB</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="违约金">
                        <el-input-number v-model="caseinfo.debt.liquidated" :min="0" controls-position="right"
                            @change="calculateTotalAmount">
                            <template #suffix>
                                <span>RMB</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="手续费">
                        <el-input-number v-model="caseinfo.debt.commission" :min="0" controls-position="right"
                            @change="calculateTotalAmount">
                            <template #suffix>
                                <span>RMB</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="其他费用">
                        <el-input-number v-model="caseinfo.debt.otherFee" :min="0" controls-position="right"
                            @change="calculateTotalAmount">
                            <template #suffix>
                                <span>RMB</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                </template>
                <div class="button-container">
                    <el-button type="primary" @click="showAdvancedFields = !showAdvancedFields" class="dropdown-button">
                        <el-icon>
                            <arrow-down v-if="!showAdvancedFields" />
                            <arrow-up v-else />
                        </el-icon>
                        {{ showAdvancedFields ? '收起' : '展开' }}
                    </el-button>
                </div>
            </div>

            <el-form-item label="还款总金额">
                <el-input class="total-amount-input" :precision="2" v-model="caseinfo.debt.amount" :min="0"
                    :disabled="true">
                    <template #suffix>
                        <span>RMB</span>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="还款方案">
                <el-button @click="openChoseRepayDialog()">点击选择</el-button>
            </el-form-item>

            <el-form-item label="案件经过">
                <el-input v-model="caseOverview" minlength="10" type="textarea" />
            </el-form-item>
            <el-form-item label="案由" maxlength="10" show-word-limit>
                <div class="cause-input-wrapper">
                    <div class="cause-input"><el-input v-model="caseinfo.cause" /></div>
                    <div class="cause-button"><el-button type="primary" :icon="Pointer" size="large" :loading="isGetting" @click="handleGetRecommendCasue"
                            circle /></div>
                </div>
            </el-form-item>
            <div class="button-container">
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button @click="onSave">保存</el-button>
            </div>
        </el-form>
        <el-dialog v-model="choseRepayDialog" title="还款方案" width="30%">
            <el-checkbox-group v-model="choseRepay">
                <div v-for="repayment in repayments" :key="repayment.repaymentId">
                    <el-checkbox :label="repayment.ruleName" :value="repayment.repaymentId" >
                    </el-checkbox>
                </div>
            </el-checkbox-group>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="choseRepayDialog = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { ArrowDown, ArrowUp, Pointer } from '@element-plus/icons-vue'
import { getRepaymentListByInsId } from '@/axios/case/repaymentReq'
import { useRouter } from 'vue-router'
import useUserStore from '@/stores/userStore'
import useApplicantStore from '@/stores/applicantStore'
import { addCase, addCaseRepayment, applyCase } from '@/axios/case/caseReq'
import { getCauseRecommend } from '@/axios/applicant/applicantReq'
import { Case } from '@/types/response/case'
import Debt from '@/types/response/debt'
import Respondent from '@/types/response/respondent'
import { TimeUtil } from '@/utils/timeUtil'
import Repayment from '@/types/response/repayment'
import Notice from '@/utils/notice'
import { Ref } from 'vue'
// do not use same name with ref
const caseinfo = reactive(new Case())
caseinfo.debt = reactive(new Debt())
caseinfo.respondent = reactive(new Respondent())
const userStore = useUserStore()
const applicantStore = useApplicantStore()
const router = useRouter()
const choseRepay = ref([]);
let applicantId = null
let applicantInsId = null
let caseOverview = ref("")


const onSubmit = async () => {
    try {
        let newCaseInfo = await applyCase(caseinfo);
        caseinfo.caseId = newCaseInfo.caseId
        await addCaseRepayment(caseinfo.caseId, choseRepay.value)
        Notice.success('案件提交成功');
        resetForm()
        router.push("/applicant/history")
    } catch (error) {
        console.error('提交案件时出错:', error);
        Notice.error('申请案件时出错，请重试');
    }
}
const onSave = async () => {
/*     console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    console.log(choseRepay.value) */
     try {
         const newCaseInfo = await addCase(caseinfo); // 声明 newCaseInfo 变量
         caseinfo.caseId = newCaseInfo.caseId;
         await addCaseRepayment(caseinfo.caseId, choseRepay.value); // 使用 await 确保操作完成后再继续
         // 弹窗提醒
         Notice.success('案件保存成功');
         resetForm()
         router.push("/applicant/history")
     } catch (error) {
         console.error('保存案件时出错:', error);
         Notice.error("保存案件时出错，请重试");
     }
}

const resetForm = () => {
    // 重置 caseinfo 对象
    const caseinfo = reactive(new Case())
    caseinfo.debt = reactive(new Debt())
    caseinfo.respondent = reactive(new Respondent())
    caseinfo.aptId = applicantId

    // 重置其他相关字段
    choseRepay.value = [];
    showAdvancedFields.value = false;
}
onMounted(() => {
    applicantId = userStore.userId
    applicantInsId = applicantStore.applicantInsId
    caseinfo.aptId = applicantId
    caseinfo.debt.annualRate = 0
    caseinfo.debt.overdueRate = 0
})
const showAdvancedFields = ref(false)
const choseRepayDialog = ref(false)
const isGetting = ref(false)
const calculateTotalAmount = () => {
    if (caseinfo.debt.principal != null
        && caseinfo.debt.principal != 0
        && caseinfo.debt.loanDate != null
        && caseinfo.debt.repayDate != null
    ) {

        // 简单的计算示例，可以根据实际需求调整
        const principal = caseinfo.debt.principal
        const annualRate = caseinfo.debt.annualRate
        const overdueRate = caseinfo.debt.overdueRate || 0
        const lateFee = caseinfo.debt.lateFee || 0
        const penalty = caseinfo.debt.liquidated || 0
        const serviceFee = caseinfo.debt.commission || 0
        const otherFees = caseinfo.debt.otherFee || 0

        // 计算还款总金额
        let totalAmount = 0
        let interest = 0
        let extraInterest = 0

        if (TimeUtil.timeCmp(new Date(), TimeUtil.strToDate(caseinfo.debt.repayDate)) <= 0) {
            let days = TimeUtil.getDayComputed(TimeUtil.strToDate(caseinfo.debt.loanDate), new Date())
            interest = (principal * annualRate / 100) * days / 365;
            totalAmount = principal + interest + extraInterest + overdueRate + lateFee + penalty + serviceFee + otherFees
        }
        else {
            let days = TimeUtil.getDayComputed(TimeUtil.strToDate(caseinfo.debt.loanDate), TimeUtil.strToDate(caseinfo.debt.repayDate))
            let fineDays = TimeUtil.getDayComputed(TimeUtil.strToDate(caseinfo.debt.repayDate), new Date())
            interest = (principal * annualRate / 100) * days / 365;
            extraInterest = (principal * annualRate / 100) * fineDays / 365 * (1 + overdueRate / 100);
            totalAmount = principal + interest + extraInterest + overdueRate + lateFee + penalty + serviceFee + otherFees
        }
        caseinfo.debt.amount = parseFloat(totalAmount.toFixed(2))
        caseinfo.debt.interest = parseFloat(interest.toFixed(2))
        caseinfo.debt.extraInterest = parseFloat(extraInterest.toFixed(2))
    }
}
const repayments: Ref<Repayment[]> = ref([])
/* const updateRepayments = (value) => {
    if (choseRepay.value.includes(value)) {
        choseRepay.value = choseRepay.value.filter(item => item !== value);
    } else {
        choseRepay.value.push(value);
    }
} */
const openChoseRepayDialog = async () => {
    choseRepayDialog.value = true
    repayments.value = await getRepaymentListByInsId(applicantInsId)
}
// 监听表单字段的变化，自动计算还款总金额
watch(
    () => [
        caseinfo.debt.principal,
        caseinfo.debt.annualRate,
        caseinfo.debt.overdueRate,
        caseinfo.debt.lateFee,
        caseinfo.debt.liquidated,
        caseinfo.debt.commission,
        caseinfo.debt.otherFee,
        caseinfo.debt.loanDate,
        caseinfo.debt.repayDate
    ],
    calculateTotalAmount
)
const handleGetRecommendCasue =() =>{
    isGetting.value = true
    getRecommendCasue()
}
const getRecommendCasue = async () => {
    if (caseOverview.value.length >= 10) {
        try {
            caseinfo.cause = await getCauseRecommend(caseOverview.value)
            isGetting.value = false
        }
        catch (error) {
            console.error('获取推荐案由时出错:', error);
            Notice.error("获取推荐案由时出错");
            isGetting.value = false
        }
    }
    else {
        Notice.notificationWaring("警告", "案件经过描述字数过少，请输入至少10个字")
    }

}
</script>

<style>
.wrapper {
    width: 80%;
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
}

.applied-wrapper {
    width: auto;
    height: auto;
    border: 1px solid rgb(177.3, 179.4, 183.6);
    border-radius: 6px;
    margin-bottom: 20px;
}

.applied-content {
    padding-left: 30px;
    padding-right: 40px;
}

.applied-content-up {
    text-align: center;
    margin-top: 30px;
    margin-bottom: 15px;
}

.applied-content-down {
    margin-bottom: 30px;
    border-top: 1px solid rgb(177.3, 179.4, 183.6)
}

.applied-content-down-item-first {
    margin-top: 30px;
}

.button-container {
    display: flex;
    justify-content: flex-end;
    /* 将按钮移到右侧 */
}

.dropdown-button {
    display: flex;
    align-items: center;
}

.total-amount-input {
    width: 150px;
}

.cause-input-wrapper {
    display: flex;
    justify-content: space-between;
    width: 100%;
}

.cause-input {
    width: 200px;
}
.cause-button{
    margin-right: 200px;
}
</style>